package com.weifly.jettycn;

import java.io.IOException;
import java.io.Writer;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;

import com.weifly.jettycn.domain.Catalog;
import com.weifly.jettycn.service.IProjectService;
import com.weifly.jettycn.util.PageInfo;
import com.weifly.jettycn.util.QueryInfo;

/**
 * 工具类
 * 
 * @author weijx
 * @date 2011-10-05
 */
public class JettycnUtil {
	
	private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	/**
	 * spring容器
	 */
	public static ApplicationContext appCtx;

	/**
	 * 创建QueryInfo
	 */
	public static QueryInfo createQueryInfo(HttpServletRequest request){
		QueryInfo qi = new QueryInfo();
		
		// 页数
		String page = request.getParameter("page");
		try{
			int p = Integer.parseInt(page);
			if(p<1){
				p = 1;
			}
			qi.setPage(p);
		}catch(NumberFormatException ne){
			qi.setPage(1);
		}
		
		// 每个记录数
		qi.setPageCount(15);
		
		return qi;
	}
	
	/**
	 * 输出分页栏
	 * 
	 * @param paramMap 分页参数
	 */
	public static void outPagebar(HttpServletRequest request, Writer writer, PageInfo pageInfo, String url, Map<String, String> paramMap) throws IOException {
		writer.write("<div class=\"pagination\">");
		String aurl = request.getContextPath() + url;
		
		// 计算总页数
		int totalPage = pageInfo.getTotal() % pageInfo.getPageCount();
		if(totalPage==0){
			totalPage = pageInfo.getTotal() / pageInfo.getPageCount();
		}else{
			totalPage = (pageInfo.getTotal() / pageInfo.getPageCount()) + 1;
		}
		// 计算开始页
		int startPage = pageInfo.getPage() - 5;
		if(startPage<1){
			startPage = 1;
		}
		// 计算结束页
		int endPage = pageInfo.getPage() + 5;
		if(endPage>totalPage){
			endPage = totalPage;
		}
		// 第一页
		if(totalPage>0){
			if(pageInfo.getPage()==1){
				writer.write("<span class=\"disabled page_first\">« 第一页</span>");
			}else{
				paramMap.put("page", "1");
				String temp = generateURL(aurl, paramMap);
				writer.write("<a class=\"page_first\" href=\"" + temp + "\">« 第一页</a>");
			}
		}
		// 中间页码
		for(int i=startPage; i<=endPage; i++){
			if(pageInfo.getPage()==i){
				writer.write("<span class=\"page_current\">" + i + "</span>");
			}else{
				paramMap.put("page", String.valueOf(i));
				String temp = generateURL(aurl, paramMap);
				writer.write("<a href=\"" + temp + "\">" + i + "</a>");
			}
		}
		// 最后页
		if(totalPage>0){
			if(pageInfo.getPage()==totalPage){
				writer.write("<span class=\"disabled page_last\">最后页 »</span>");
			}else{
				paramMap.put("page", String.valueOf(totalPage));
				String temp = generateURL(aurl, paramMap);
				writer.write("<a class=\"page_last\" href=\"" + temp + "\">最后页 »</a>");
			}
		}
		writer.write("</div>");
	}
	
	private static String generateURL(String url, Map<String, String> paramMap){
		StringBuilder sb = new StringBuilder(url);
		int i=0;
		for(String key : paramMap.keySet()){
			String val = paramMap.get(key);
			if(StringUtils.isNotEmpty(val)){
				if(i==0){
					sb.append("?").append(key).append("=").append(val);
				}else{
					sb.append("&").append(key).append("=").append(val);
				}
				i++;
			}
		}
		return sb.toString();
	}
	
	/**
	 * 翻译catalog
	 */
	public static String translateCatalog(String catalogid){
		IProjectService ps = (IProjectService)appCtx.getBean("projectService");
		Catalog catalog = ps.getCatalog(catalogid);
		if(catalog!=null){
			return catalog.getName();
		}else{
			return "";
		}
	}
	
	/**
	 * 格式化date
	 */
	public static String formatDate(Date date, String format){
		if(date==null){
			return "";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}
	}
	
	/**
	 * 格式化date
	 */
	public static String formatDate(Date date){
		if(date==null){
			return "";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(date);
		}
	}
	
	/**
	 * 格式化date
	 */
	public static String formatDateTime(Date date){
		if(date==null){
			return "";
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(date);
		}
	}
	
	public static Date parseDate(String dateStr) throws ParseException{
		if(dateStr==null){
			return null;
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.parse(dateStr);
		}
	}
	
	/**
	 * 得到uuid
	 * 
	 * @return
	 */
	public static String getUuid() {
		try {
			UUID uuid = UUID.randomUUID();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(uuid.toString().getBytes());
			char[] chars = encodeHex(md5.digest());
			return new String(chars);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static char[] encodeHex(byte[] data) {
		int l = data.length;
		char[] out = new char[l << 1];
		// two characters form the hex value.
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
			out[j++] = DIGITS[0x0F & data[i]];
		}
		return out;
	}
	
	public static boolean stringEquals(String s1, String s2){
		if(s1==null || s1.isEmpty()){
			return (s2==null || s2.isEmpty());
		}else{
			return s1.equals(s2);
		}
	}
	
	public static String htmlspecialchars(String str) {
		if(str==null){
			return "";
		}
		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		return str;
	}
}
